<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-8-13
 * Time: 下午6:06
 * To change this template use File | Settings | File Templates.
 */
class Model_Pay_99bill extends MY_Model
{
    /**
     * 支付渠道配置
     * @var array
     */
    private $conf = array();

    public function __construct()
    {
        $this->conf['merchant_id'] = config_item('99bill_merchant_id');   //商户号
        $this->conf['merchant_key'] = config_item('99bill_merchant_key'); //密钥
        $this->conf['action_url'] = config_item('99bill_request_url');    //支付接口地址
        $this->conf['InputCharset'] = 1;                        //字符集 1 utf-8
        $this->conf['PayType'] = '00';
        $this->conf['Language'] = 1;
        $this->conf['SignType'] = 1;                            //签名类型1 md5
        $this->conf['Version'] = 'v2.0';                        //块钱接口版本
        $this->conf['payback'] = config_item('pay_back_url'); //支付完毕回调地址
        $this->conf['redoFlag'] = '1';
        $this->conf['pid'] = '';
    }

    /******************************************请求****************************************/
    public function request(array $arr)
    {
        $input['inputCharset'] = $this->conf['InputCharset'];
        $input['bgUrl'] = $this->conf['payback'];
        $input['version'] = $this->conf['Version'];
        $input['language'] = $this->conf['Language'];
        $input['signType'] = $this->conf['SignType'];
        $input['merchantAcctId'] = $this->conf['merchant_id'];
        $input['payerName'] = $arr['payerName'];
        $input['payerContactType'] = '1';
        $input['payerContact'] = '';
        $input['orderId'] = $arr['order_sn'];
        $input['orderAmount'] = $arr['amount'] * 100;
        $input['orderTime'] = date('YmdHis');
        $input['productName'] = $arr['name'];
        $input['productNum'] = '';
        $input['productId'] = '';
        $input['productDesc'] = '';
        $input['ext1'] = '';
        $input['ext2'] = '';
        $input['payType'] = $this->conf['PayType'];
        $input['bankId'] = $arr["bank"];
        $input['redoFlag'] = $this->conf['redoFlag'];
        $input['pid'] = $this->conf['pid'];
        $input['signMsg'] = $this->sign($input);
        return $this->makeRequest($this->conf['action_url'], $input);
    }

    /******************************************响应****************************************/
    function response()
    {
        $input['merchantAcctId'] = ($this->input->get_post('merchantAcctId') == $this->conf['merchant_id']) ? $this->conf['merchant_id'] : '';
        //获取网关版本.固定值
        ///快钱会根据版本号来调用对应的接口处理程序。
        ///本代码版本号固定为v2.0
        $input['version'] = $this->input->get_post('version');
        //获取语言种类.固定选择值。
        ///只能选择1、2、3
        ///1代表中文；2代表英文
        ///默认值为1
        $input['language'] = $this->input->get_post('language');
        //签名类型.固定值
        ///1代表MD5签名
        ///当前版本固定为1
        $input['signType'] = $this->input->get_post('signType');
        //获取支付方式
        ///值为：10、11、12、13、14
        ///00：组合支付（网关支付页面显示快钱支持的各种支付方式，推荐使用）10：银行卡支付（网关支付页面只显示银行卡支付）.11：电话银行支付（网关支付页面只显示电话支付）.12：快钱账户支付（网关支付页面只显示快钱账户支付）.13：线下支付（网关支付页面只显示线下支付方式）.14：B2B支付（网关支付页面只显示B2B支付，但需要向快钱申请开通才能使用）
        $input['payType'] = $this->input->get_post('payType');
        //获取银行代码
        ///参见银行代码列表
        $input['bankId'] = $this->input->get_post('bankId');
        //获取商户订单号
        $input['orderId'] = $this->input->get_post('orderId');
        //获取订单提交时间
        ///获取商户提交订单时的时间.14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
        ///如：20080101010101
        $input['orderTime'] = $this->input->get_post('orderTime');
        //获取原始订单金额
        ///订单提交到快钱时的金额，单位为分。
        ///比方2 ，代表0.02元
        $input['orderAmount'] = $this->input->get_post('orderAmount');
        //获取快钱交易号
        ///获取该交易在快钱的交易号
        $input['dealId'] = $this->input->get_post('dealId');
        //获取银行交易号
        ///如果使用银行卡支付时，在银行的交易号。如不是通过银行支付，则为空
        $input['bankDealId'] = $this->input->get_post('bankDealId');
        //获取在快钱交易时间
        ///14位数字。年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]
        ///如；20080101010101
        $input['dealTime'] = $this->input->get_post('dealTime');
        //获取实际支付金额
        ///单位为分
        ///比方 2 ，代表0.02元
        $input['payAmount'] = $this->input->get_post('payAmount');
        //获取交易手续费
        ///单位为分
        ///比方 2 ，代表0.02元
        $input['fee'] = $this->input->get_post('fee');
        //获取扩展字段1
        $input['ext1'] = $this->input->get_post('ext1');
        //获取扩展字段2
        $input['ext2'] = $this->input->get_post('ext2');
        ///10代表 成功; 11代表 失败
        ///00代表 下订单成功（仅对电话银行支付订单返回）;01代表 下订单失败（仅对电话银行支付订单返回）
        $input['payResult'] = $this->input->get_post('payResult');
        ///详细见文档错误代码列表
        $input['errCode'] = $this->input->get_post('errCode');
        //获取加密签名串

        $sign = $this->input->get_post('signMsg');

        $rData = array(
            'result' => $input['payResult'],
            'third_part_order_sn' => $input['dealId'],
            'amount' => ($input['payAmount']/100),
            'order_sn' => $input['orderId'],
            'pay_user' => '',
            'pay_user_id' => '',
            'request_type' => $this->input->get_post('view') ? 1:2,
            'pay_channel' => $input['bankId'],
            'bank_order_id' => $input['bankDealId'],
            'pay_type' => '99bill',
            'response' => "<result>1</result><redirecturl>{$this->conf['payback']}?view=1</redirecturl>",
        );

        $my_sign = $this->sign($input);

        //状态值(status) 1 成功， 2 签名错误， 3 订单支付失败
        $rData['status'] = 1;
        if (strtoupper($sign) !== $my_sign) {
            $rData['status'] = 2;
        }
        //判断支付状态
        if ($input['payResult'] != '10') {
            $rData['status'] = 3;
        }
        return $rData;
    }

    private function makeRequest($api='' ,$data=array())
    {
        $form = "<form method=\"POST\" name=\"pay_form\" action=\"{$api}\">\n";
        foreach($data as $name=>$value)
        {
            $form .= "<input type=\"hidden\" name=\"{$name}\" value=\"{$value}\">\n";
        }
        $form .= "</form>\n";
        $form .= "<script>document.forms['pay_form'].submit()</script>";
        return $form;
    }

    private function sign($data)
    {
        $sign = '';
        foreach($data as $k=>$v)
        {
            $v && $sign .= "{$k}={$v}&";
        }
        $sign .= "key=".$this->conf['merchant_key'];
        return strtoupper(md5($sign));
    }
}